<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 拼车 -->
    <script>
      var carPooling = function (trips, capacity) {
        // 行程单按站点顺序排序
        trips = trips.sort((a, b) => a[1] - b[1])
        // 每个站点乘客人数表
        const passengers = {}
        // 按行程单顺序每个站点上车的人数
        for (let i = 0; i < trips.length; i++) {
          const item = trips[i]
          // console.log(start, item[1])
          let start = item[1]
          let s = 0
          // 注意计算上车人数时，passengers【途径站】也要加，因为有可能是后面行程的上车站，passengers【下车站】我们不用加人数
          while (s < item[2] - item[1]) {
            // console.log(start + s, ~~passengers[start + s] + item[0]);
            passengers[start + s] = ~~passengers[start + s] + item[0]
            // 某个接客站点超员，直接返回false
            if (passengers[start + s] > capacity) return false
            s++
          }
        }
        return true
      }
      console.log(
        carPooling(
          [
            [2, 1, 5],
            [3, 3, 7]
          ],
          4
        )
      )
    </script>
  </body>
</html>
